import os
import re
import sys
import json
import shutil

def writeFile(fileName,content):
    with open(fileName,"w+") as file:
        file.write(content)

def readFile(fileName):
    with open(fileName,"r") as file:
        return file.read()

def newPost(postName):
    # 默认在当前目录创建文章，若发现有content目录则在content目录下创建文章
    postPath = "./"
    if os.path.exists("content") and os.path.isdir("content"):
        postPath = "content/"

    os.mkdir(postPath+postName)
    os.mknod(postPath+postName+"/"+postName+".html")

def newSite(siteName):
    sitePath = "./" + siteName + "/"
    os.mkdir(sitePath)
    os.mkdir(sitePath + "content")
    os.mkdir(sitePath + "themes")

    writeFile(sitePath + "config.json", json.dumps({
        'siteName' : siteName,
        'toUrl' : 'http://localhost:8080',
        'theme' : 'book',
        'briefLong' : 75
    }, sort_keys = True, indent = 4))

def newTheme(themeName):
    # 默认在当前文件夹创建主题，若发现themes目录则在themes目录中创建主题
    themePath = "./"
    if os.path.exists("themes") and os.path.isdir("themes"):
        themePath = "themes/"

    themePath = themePath + themeName + "/"
    os.mkdir(themePath)

    writeFile(themePath + "list.html","""\
<div>
    <a href="{{tmp.path}}">
        {{tmp.title}}
    </a>
    <p>{{tmp.brief}}</p>
</div>
    """)
    writeFile(themePath + "post.html","""\
<!DOCTYPE html>
<html>
    <head>
        <title>{{tmp.title}}</title>
    </head>
    <body>
        <main>{{tmp.content}}</main>
    </body>
</html>
    """)
    writeFile(themePath + "index.html","""\
<!DOCTYPE html>
<html>
    <head>
        <title>{{config.siteName}}</title>
    </head>
    <body>
        <main>{{tmp.list}}</main>
    </body>
</html>
    """)

# pack
def filterFile(path):
    htmlFile = []
    for dir in os.listdir(path):
        dirPath = path + "/" + dir
        if os.path.isdir(dirPath):
            htmlFile = htmlFile + filterFile(dirPath)
        elif dir[-5:] == ".html":
            htmlFile.append(dirPath)

    return htmlFile

def parse(string, dict):
    tmp = ""
    string = string + "."
    for char in string:
        # 遇到.就将dict设置为dict[tmp]的内容
        if char == '.':
            dict = dict[tmp]
            tmp = ""
        else:
            tmp = tmp + char

    return dict

def extractKey(fileName):
    return set(re.findall("{{(.*)}}",readFile(fileName)))

def replaceKey(file, keyDict, message):
    fileContent = readFile(file)
    for key in keyDict:
        fileContent = fileContent.replace("{{" + key + "}}", parse(key, message))

    return fileContent

def pack():
    message = {}
    message["tmp"] = {}
    message["tmp"]["list"] = ""
    message["config"] = json.loads(readFile("config.json")) 
    themePath = "themes/" + message["config"]["theme"] + "/"

    themeKey = {}
    themeKey["index"] = extractKey(themePath + "index.html")
    themeKey["list"] = extractKey(themePath + "list.html")
    themeKey["post"] = extractKey(themePath + "post.html")

    # 制作finish
    shutil.copytree("content","finish")
    htmlFile = filterFile("finish")
    for dir in htmlFile:
        message["tmp"]["path"] = dir[7:]
        message["tmp"]["title"] = dir[7:-5]
        message["tmp"]["content"] = readFile(dir)
        message["tmp"]["brief"] = message["tmp"]["content"][:int(message["config"]["briefLong"])]

        message["tmp"]["list"] = message["tmp"]["list"] + replaceKey(themePath + "list.html", themeKey["list"], message)

        writeFile(dir, replaceKey(themePath + "post.html", themeKey["post"], message))

    # index.html
    writeFile("finish/index.html", replaceKey(themePath + "index.html", themeKey["index"], message))
    shutil.copytree(themePath, "finish/theme")



# main
argv = sys.argv[1:]

if len(argv) == 0:
    print("""\
catt
--------------------------
catt new site [siteName]
catt new theme [themeName]
catt new post [postName]
catt pack""")

else:
    if argv[0] == "new":
        if argv[1] == "post":
            newPost(argv[2])
        elif argv[1] == "site":
            newSite(argv[2])
        elif argv[1] == "theme":
            newTheme(argv[2])
        else:
            raise Exception("ERROR argv: " + argv[1])

    elif argv[0] == "pack":
        pack()
    else:
        raise Exception("ERROR argv: " + argv[0])


